<?php
/**
 * 砍价活动订单表
 *
 * Date: 2017/7/18
 * Time: 11:12
 */

defined('InNcPHP') or exit('Access Invalid!');
header("Content-Type: text/html;charset=utf-8");
class bargain_orderControl extends BaseHomeControl {

    public $redis;

    public $deploy;
    private $fileCharset = "UTF-8";
    public $postCharset = "UTF-8";
    public  function  __construct()
    {
        parent::__construct();
        $this->redis = new Redis();
        $this->deploy = C('redis');
        $this->redis->connect($this->deploy['master']['host'],$this->deploy['master']['port']);
        Tpl::setLayout('bargain_layout');
        Tpl::setDir('bargain');
    }


    public  function  indexOp(){

        $this->redis->set($this->deploy['prefix'].'payorder-'.'100','ing',30);
        //var_dump($this->redis->get($this->deploy['prefix'].'payorder-'.'100'));
        $bargain_order_model = Model('bargain_order');
        $bargain_model = Model('bargain');
        $member_id = $_SESSION['member']['member_id'];
        $condition = array();
        $condition['member_id'] = $member_id;
        $order_list = $bargain_order_model->getBgOrderListPage($condition,'*',10,'bg_order_id desc');
        foreach ($order_list as $k=>$v){
            $end_time = $bargain_model->getBargainInfo(array('bargain_id'=>$v['bargain_id']),'end_time');
            $order_list[$k]['end_time'] = $end_time['end_time'];
        }
        Tpl::output('order_list',$order_list);
        //ajax 加载分页
        if (isset($_GET['isajax']) && $_GET['isajax'] == 1) {
            Tpl::showpage('bargain_order_page', 'null_layout');
            exit;
        }
        Tpl::output('TotalNum',pagecmd("gettotalnum"));
        Tpl::output('TotalPage',pagecmd("gettotalpage"));
        Tpl::output('member_name',$_SESSION['member']['nickname']);

        Tpl::showpage('bargain_order');

    }
    /**
     * 单个订单砍价排行榜
     */

    public function ranking_listOp(){
        $order_id = intval($_GET['order_id']);
        $bargain_count_model = Model('bargain_count');
        if(empty($order_id)){
            showMessage('参数有误','','html','error');
        }
        $res = $this->redis->getKeys($this->deploy['prefix'].'orderu-'.$order_id."*");//去缓存查询帮砍人数信息
        $count_civil = array();
        if(!empty($res)){
            foreach($res as $k ){
                $count_civil[] = $this->redis->hGetAll($k);
            }
        }
        $arr = array();
        foreach($count_civil as $key ){
           $arr[] = $key['cuont_sunm'];
        }
        array_multisort($arr, SORT_DESC, $count_civil);
        $condition = array();
        $condition['bg_order_id'] = $order_id;
        $condition['paid_sunm'] = array('gt',0);
        //$count_civil = $bargain_count_model->getCountPage(array('bg_order_id'=>$order_id),'*','','cuont_sunm desc');
        $paid_civil  = $bargain_count_model->getCountPage($condition,'*','','paid_sunm desc');

        Tpl::output('count_civil',$count_civil);//获取帮砍价榜
        Tpl::output('paid_civil',$paid_civil);//获取代付榜
        Tpl::showpage('bargain_ranking');
    }

    /**
     * 检查用户提价订单是否合法
     */

    public function  check_orderOp(){

        $order_id = intval($_POST['order_id']);
        $bargain_id = intval($_POST['bargain_id']);
        $order_model = Model('bargain_order');
        $bargain_model = Model('bargain');
        //检查活动订单是否存在
        $res = $order_model->Checkismeorder($order_id,$_SESSION['member']['member_id'],$bargain_id);
        if(empty($res)){
            output_error('参数有误');
        }
        //订单信息
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));

        //获取活动信息
        $bargain_info = $bargain_model->checkActivity($bargain_id);
        if(empty($bargain_info)){
            output_error('您来晚啦,活动已过期！');
        }
        if($bargain_info['is_hot']==1){
            //属于爆款,判断是否砍到底价
            if($order_info['bg_order_price']>$order_info['bg_floorprice']){
                output_error('您还没有砍到最低价噢！快去找好友帮忙吧！');
            }
            if(empty($order_info['min_time'])){
                output_error(array('code'=>'-200','msg'=>'很抱歉,名额已满！'));
            }else{
                $data = array();
                $data['code'] = 200;
                $data['datas'] = array('code'=>'200','msg'=>'祝贺您,抢爆成功！');
                echo json_encode($data);
                return true;
            }

        }else {
            if($bargain_info['bg_store']<=$bargain_info['bg_true_rs']){
                output_error(array('code'=>'-200','msg'=>'很抱歉,您下手晚啦！'));
            }else {
                $data = array();
                $data['code'] = 200;
                $data['datas'] = '提交订单成功';
                echo json_encode($data);
                return true;
            }

        }
 }

    /**
     * 用户填写收货信息
     */
    public function member_addressOp(){
        $order_id = intval($_GET['order_id']);
        $order_model = Model('bargain_order');
        $bargain_model = Model("bargain");
        $member_merchant_model = Model('member_merchant');
        $type = intval($_GET['type']);
        if(chksubmit()){
            //output_error('支付繁忙,请您稍后再试！');
           //$re = $this->check_orderOp();

               //redis 缓存中查询有无朋友正在帮代付
             if($this->redis->get($this->deploy['prefix'].'payorder-'.$order_id)){

                   output_error('支付繁忙,请您稍后再试！');
               }
               //验证成功 用户收货信息写入订单表

               $condition = array();
               $condition['bg_order_id'] = $_POST['order_id'];
               $condition['bargain_id']  = $_POST['bargain_id'];
               $result = array();
               $result['address_name']   = $_POST['minute_address'];
               //$result['bg_order_status']= 30;
               $result['cnee_name']      = $_POST['cnee_name'];
               $result['cnee_tel']       = $_POST['phone'];
               $result['city_id']        = $_POST['sheng'];
               $result['shi_id']         = $_POST['shi'];
               $result['qu_id']          = $_POST['qu'];
               $result['bg_order_sn']    = str_pad($_SESSION['member']['member_id'], 11, strrev(time())) . mt_rand(100000, 999999);
               $order_model->updateBgOrder($condition,$result);
               $bg_order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$_POST['order_id']));
               if($bg_order_info['bg_order_price']=='0'){


                   //已经砍到最低价直接生成订单改变参数


                       //实体店订单
                       $outcome = array();
                       $rand_code = '';
                       $outcome['pay_time'] = time();
                       $outcome['bg_order_status'] = 20;
                       if($bg_order_info['type'] == '1'){
                           //生成兑换码
                           $rand_code = '';
                           for ($i = 0; $i < 16; $i++) {
                               $rand_code .= mt_rand(0, 10);
                           }
                           $code = str_pad($bg_order_info['member_id'].($bg_order_info['bg_order_id']+$bg_order_info['merchant_id']+$bg_order_info['merchant_id']),16,$rand_code);//生成兑换码
                           $outcome['bg_order_code'] = $code;
                       }

                       $res = $order_model->updateBgOrder(array('bg_order_id'=>$bg_order_info['bg_order_id']),$outcome);
                       $bargain_model->true_member($bg_order_info['bargain_id']);
                       $bargain_model->reduce_store($bg_order_info['bargain_id']);
                       if($res){
                           output_data('订单提交成功');
                       }

               }else{
                   $res = $this->redis->set($this->deploy['prefix'].'payorder-'.$order_id,'ing',30);
                   if($res){
                       //返回支付需要的参数
                       $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$_POST['order_id']));
                       //获取商家子商户号
                       $merchant_code = $member_merchant_model->getMerchantInfo(array('merchant_id'=>$order_info['$order_info']),'submch_id');
                       if($this->is_weixin()){
                           $data = $this->gzpayOp($order_info,$merchant_code['submch_id']);
                       }else{
                           $data = $this->saomazhifuOp($order_info,$merchant_code['submch_id']);
                       }
                       echo $data;
                       //var_dump(json_encode());
                       exit;
                   }
               }




        }
        //输出一级地区
        $model_area = Model('area');
        $condition = array();
        $condition['parent_id'] = 1;
        $area_list = $model_area->getAreaList($condition, 'area_id,name');
        //订单信息
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
        Tpl::output('order_info',$order_info);
        Tpl::output('area_list',$area_list);
        Tpl::output('order_id',$order_id);
        Tpl::output('is_weixin',$this->is_weixin());
        Tpl::output('type',$type);
        Tpl::showpage('address');


    }

    /**
     * 地区列表
     */
    public function area_listOp() {
        $area_id = intval($_POST['area_id']);

        $model_area = Model('area');

        $condition = array();
        if($area_id > 0) {
            $condition['parent_id'] = $area_id;
        } else {
            $condition['area_deep'] = 1;
        }
        $area_list = $model_area->getAreaList($condition, 'area_id,name');
        output_data(array('area_list' => $area_list));
    }

    /**
     * 检查该订单是否可以代付
     */
    public function check_payOp(){

        $order_id = intval($_POST['order_id']);
        $bargain_id = intval($_POST['bargain_id']);
        $order_model = Model('bargain_order');
        $bargain_model = Model('bargain');
        $bargain = $bargain_model->checkActivity($bargain_id);
        if(empty($bargain)){
            output_error('活动已过期');
        }
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
        if($bargain['is_hot'] ==1 && $order_info['bg_order_price']>$order_info['bg_floorprice']){
            output_error('该活动需砍到最低价才可以代付噢！');
        }
        if($order_info['bg_order_price']=='0'){
            output_error('该订单已到最低价,感谢您的心意！');
        }
        output_data('OK');
    }


    /**
     * 朋友代付
     */
    public function friend_payOp(){

        $order_model = Model('bargain_order');
        $bargain_model = Model('bargain');
        $member_merchant_model = Model('member_merchant');
        $order_id = intval($_GET['order_id']);
        $bargain_id = intval($_GET['bargain_id']);
        $bargain_paid_model = Model('bargain_paid');
        $bargain_count = Model('bargain_count');
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
        $bargain = $bargain_model->checkActivity($bargain_id);
        if(empty($order_info)){
            showMessage('参数有误','','html','error');
        }
        if(empty($bargain)){
            showMessage('活动已过期','','html','error');
        }
        if($bargain['is_hot'] ==1 && $order_info['bg_order_price']>$order_info['bg_floorprice']){
            showMessage('该活动需砍到最低价才可以代付噢！','','html','error');
        }
        $arr =  explode(',',$bargain['friends_sum']);//活动设置的朋友可以代付的金额
        if(chksubmit()){
           //检查订单
            $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
            $bargain_count_info = $bargain_count->getbargain_countInfo(array('bg_order_id'=>$order_id,'member_id'=>$_SESSION['member']['member_id']));

            if(empty($bargain_count_info)){
                //生成代付信息
                $true_count = array();
                $true_count['member_id'] = $_SESSION['member']['member_id'];
                $true_count['nickname']  = $_SESSION['member']['nickname'];
                $true_count['headimgurl']= $_SESSION['member']['headimgurl'];
                $true_count['add_time']    = TIMESTAMP;
                $true_count['bg_order_id'] = $order_id;
                $bargain_count->table('bargain_count')->insert($true_count);

            }

            $pay_price = empty($_POST['price'])? $_POST['price2']:$_POST['price'];
            if($pay_price<=0){
                output_error('代付金额不能为负数!');
            }
            if($pay_price > $order_info['bg_order_price']){
                output_error('代付金额不能超过实际价格噢!');
            }
            //查询redis中有无用户在支付此订单
            if($this->redis->get($this->deploy['prefix'].'payorder-'.$order_id)){
                output_error('系统繁忙,请稍后再试!');
            }
            //生成代付订单
            $params = array();
            $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
            $params['paid_size'] = $pay_price;
            $params['member_id'] = $_SESSION['member']['member_id'];
            $params['bargain_order_id'] = $order_id;
            $params['paid_sn'] = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
            $params['pay_type'] = 0;
            $res = $bargain_paid_model->addBgpaid($params);
            if($res){
                //redis缓存中锁住该条订单的支付动作
                $this->redis->set($this->deploy['prefix'].'payorder-'.$order_id,'ing',30);
                //获取子商户号 ,支付时需要
                $merchant_code = $member_merchant_model->getMerchantInfo(array('merchant_id'=>$order_info['$order_info']),'submch_id');
                //返回支付所需要的参数
                if($this->is_weixin()){
                    $data = $this->friendpayOp($params,$merchant_code['submch_id']);
                }else{
                    $data = $this->saomazhifuOp($params,$merchant_code['submch_id']);
                }
                echo $data;
                exit;
              }




        }
        Tpl::output('friends_pay',$arr);
        Tpl::output('is_weixin',$this->is_weixin());
        Tpl::output('order_info',$order_info);
        Tpl::showpage('friend_pay');

    }

    /**
     * 订单详情
     */
    public function  order_infoOp(){


        $order_id = intval($_GET['order_id']);
        $order_model = Model('bargain_order');
        $order_sum_model = Model('bargain_count');
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));
        if(empty($order_info) || $order_info['bg_order_status']==10 || $order_info['bg_order_status']==30 ){
            showMessage('非法操作','','html','error');
        }
        //该订单代付及砍赞信息
        $condition = array();
        $condition['bg_order_id'] = $order_id;
        $res = $order_sum_model->getCountPage($condition,'cuont_sunm,paid_sunm');
        $cuont_sunm = '';
        $paid_sunm = '';
        foreach ($res as $k){
            //$cuont_sunm+= $k['cuont_sunm'];
            $paid_sunm+= $k['paid_sunm'];
        }
        //var_dump($order_info['bg_order_price']);exit;
        $data = $order_info['bg_price']-$order_info['bg_order_price'];
        $cuont_sunm = $data-$paid_sunm;
        Tpl::output('cuont_sunm',$cuont_sunm);//砍价总金额度
        Tpl::output('paid_sunm',$paid_sunm);//代付总金额
        Tpl::output('order_info',$order_info);
        Tpl::showpage('order_info');


    }


    /**
     * 确认收货操作
     */
    public function ackReceivingOp(){

        $order_id = intval($_POST['order_id']);
        $order_model = Model('bargain_order');
        $order_info = $order_model->getBgOrderInfo(array('bg_order_id'=>$order_id));

        if(empty($order_info) || $order_info['bg_order_status']!=40 ){
            output_data(false);
        }
        $res = $order_model->updateBgOrder(array('bg_order_id'=>$order_id),array('bg_order_status'=>41,'receiving_time'=>time()));
        output_data($res);

    }


    /**
     * 订单公众号支付
     */

    public function gzpayOp($params,$sogo_pay_code){

        $url = 'https://api.efujr.com:8118/wxzfservice/h5order';
        require_once BASE_DATA_PATH.'/vendors/yfpay/yifupay.php';
        $yifu = new yifupay();
        $info = array(
            'orgno'=>$yifu::ORGNO,
            'secondtimestamp'=>time(),
            'nonce_str'=>rand(10000000,99999999),
            'body'=>$params['bg_title'],
            'total_fee'=>$params['bg_order_price'],
            'T0t1'=>'T1',
            'out_trade_no'=>$params['bg_order_sn'],
            //'submch_id'=>'100003378690',//目前用这个测试
            'submch_id'=>$sogo_pay_code,  //正式部署时打开
        );
        $stringA =$yifu->getSignContent($info);
        $stringSignTemp = $yifu->getSign($stringA);
        $info['sign'] = $stringSignTemp;
        $datas = $yifu->httpPost($url,$info);
        return $datas;
    }




    /**
     * 朋友代付公众号支付
     */

    public function friendpayOp($params,$sogo_pay_code){
        $url = 'https://api.efujr.com:8118/wxzfservice/h5order';
        require_once BASE_DATA_PATH.'/vendors/yfpay/yifupay.php';
        $yifu = new yifupay();
        $info = array(
            'orgno'=>$yifu::ORGNO,
            'secondtimestamp'=>time(),
            'nonce_str'=>rand(10000000,99999999),
            'body'=>'代付订单ID'.$params['bargain_order_id'].'用户id'.$params['member_id'],
            'total_fee'=>$params['paid_size'],
            'T0t1'=>'T1',
            'out_trade_no'=>$params['paid_sn'],
            ///'submch_id'=>'100003378690',//目前用这个测试
            'submch_id'=>$sogo_pay_code,  //正式部署时打开

        );
        $stringA =$yifu->getSignContent($info);
        $stringSignTemp = $yifu->getSign($stringA);
        $info['sign'] = $stringSignTemp;
        $datas = $yifu->httpPost($url,$info);
        return $datas;

    }





    /**
     * 支付宝扫码支付
     */
    public  function saomazhifuOp($params,$sogo_pay_code){
        $url = 'https://api.efujr.com:8118/wxzfservice/order';
        require_once BASE_DATA_PATH.'/vendors/yfpay/yifupay.php';
        $yifu = new yifupay();
        $info = array(
            'orgno'=>$yifu::ORGNO,
            'secondtimestamp'=>time(),
            'nonce_str'=>rand(10000000,99999999),
            'body'=>$params['bg_title']?$params['bg_title']:'朋友代付',
            'total_fee'=>$params['paid_size']?$params['paid_size']:$params['bg_order_price'],
            'T0t1'=>'T1',
            'channel'=>'alipay',
            'out_trade_no'=>$params['bg_order_sn']?$params['bg_order_sn']:$params['paid_sn'],
            //'submch_id'=>'100003378690',
            'submch_id'=>$sogo_pay_code,  //正式部署时打开

        );
        $stringA =$yifu->getSignContent($info);

        $stringSignTemp = $yifu->getSign($stringA);


        $info['sign'] = $stringSignTemp;

        $datas = $yifu->httpPost($url,$info);
        //var_dump(json_decode($datas,true));
        return $datas;

    }





}